<template>
	<div id="app-container" class="page-container">
		<t-sticky>
		    <t-navbar title="分类" :fixed="false" left-arrow @left-click="handleBack" />
		</t-sticky>
		<div class="scroll-container" ref="scrollContainer">
			<div class="classify-box">
				<div class="classify-list" v-for="(item,index) in visibleGroups" :key="item.code">
					<span class="all" @click="handleAllClick(item.code)"
						:class="{ active: selectedMap[item.code] === 'all' }">全部</span>
					<div class="classify">
						<span v-for="(ite,inde) in item.children" :key="ite.classificationId"
							@click="handleChildClick(item.code, ite)"
							:class="{ active: selectedMap[item.code] === ite.classificationId }">{{ite.classificationName}}</span>
					</div>
				</div>
				<div class="global-toggle-btn" @click="toggleGlobal" v-if="classifyList.length > 2">
					{{ isGlobalExpanded ? '收起分类' : '展开分类' }}
				</div>
			</div>
			<div class="course-list">
				<!-- <div class="course" @click="getCourse(group)" v-for="(group,index) in courseList" :key="group.courseId">
					<div class="tu-box">
						<t-image class="image-container"
							:style="{ width: '100%', aspectRatio: '1 / 1.42',borderRadius:'6px' }" fit="fill"
							:src="group.titleImg"></t-image>
						<span :class="group.lastDetailsNameV === '完' ? 'status' : 'status1'">
						  {{group.lastDetailsNameV}}
						</span>
					</div>
					<h4>{{group.title}}</h4>
					<p>{{group.authorName}}</p>
				</div> -->
				<CoverImage class="itembox" v-for="(item, index) in courseList" :key="index"
					@click="getCourse(item)" :item="item" :cache="false"></CoverImage>
			</div>
			<view class="load-status" v-if="isLoadingMore">
			  加载中...
			</view>
			<view class="load-status" v-if="!loadMoreStatus && !isLoadingMore">
				————&nbsp;&nbsp;&nbsp;&nbsp;啊呀~到底了呢&nbsp;&nbsp;&nbsp;&nbsp;————
			</view>
		</div>
	</div>
</template>

<script setup>
	import {
		onMounted,
		ref,
		computed,
		onUnmounted,
		nextTick
	} from 'vue';
	import {
		useRouter,
		useRoute
	} from 'vue-router';
	import {
		getClassifyType,
		getCommicList
	} from '@/api/index.js';
	import DownloadApk from "@/components/downloadApk.vue";
	import CoverImage from '@/components/CoverImage';

	const router = useRouter();
	const route = useRoute();

	const classifyText = ref();
	const classifyList = ref([]);
	const courseList = ref([]);
	const isGlobalExpanded = ref(false);
	const isShowDialog = ref(false);
	const classifyId = ref(''); // 存储从路径参数获取的分类ID（如123）
	const lastScrollTop = ref(0);
	const selectedMap = ref({}); // 存储每个大分类的选中状态
	const loading = ref(false); // 初始加载状态
	const localClassifyId = ref(0);
	const loadMoreStatus = ref(true); // 'more'/'loading'/'nomore'
	const scrollContainer = ref(null); // 滚动容器引用
	let isLoadingMore = false; // 防止重复请求（局部变量，不响应式）
	const params = ref({
		'page': 1,
		'limit': 12,
		'classifyId': '', // 用于接口请求的分类ID
	});
	const pageInfo = ref({
		page: 1,
		limit: 12,
		totalPage: null
	});

	// 获取分类数据
	const getClassifyData = async () => {
		try {
			const res = await getClassifyType();
			classifyList.value = res.data || [];
			// 初始化选中状态（默认全选“全部”）
			const initSelectedMap = {};
			classifyList.value.forEach((group) => {
				initSelectedMap[group.code] = 'all';
			});
			selectedMap.value = initSelectedMap;
			updateClassifyIdParam();
		} catch (error) {
			console.error('获取分类数据失败:', error);
		}
	};

	// 获取漫画数据
	const getCourseData = async () => {
		loading.value = true;
		try {
			const date = await getCommicList(params.value);
			const res = date.data;
			courseList.value = res.list ;
			pageInfo.value = {
				...pageInfo.value,
				totalPage: res.totalPage,
				page: res.currPage
			};
			loadMoreStatus.value = res.totalPage > res.currPage;
		} catch (error) {
			// console.error('获取课程数据失败:', error);
		}
	};
	// 上拉加载更多
	const loadMore = async () => {
		// 阻止重复请求或已到底
		if (isLoadingMore || pageInfo.value.page >= pageInfo.value.totalPage) {
			loadMoreStatus.value = false;
			return;
		}
	
		isLoadingMore = true;
		loadMoreStatus.value = true;
		try {
			const result = await getCommicList({
				page: pageInfo.value.page + 1,
				limit: pageInfo.value.limit,
				classifyId: params.value.classifyId,
				sort: 1
			});
			const res = result.data;
			courseList.value = [...courseList.value, ...res.list];
			pageInfo.value = {
				...pageInfo.value,
				totalPage: res.totalPage,
				page: res.currPage
			};
			loadMoreStatus.value = res.currPage < res.totalPage;
		} catch (err) {
			console.error('加载更多失败:', err);
			loadMoreStatus.value = true;  // 失败后允许重试
		} finally {
			isLoadingMore = false;
		}
	};
	
	const handleScroll = () => {
		// if (!scrollContainer.value) return;
		const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
		const clientHeight = window.innerHeight || document.documentElement.clientHeight;
		const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
		const distanceToBottom = scrollHeight - scrollTop - clientHeight;
		const isScrollDown = scrollTop > lastScrollTop.value;
	
		if (distanceToBottom <= 10 && isScrollDown) {
			loadMore();
		}
		lastScrollTop.value = scrollTop;
	};

	// 点击子分类
	const handleChildClick = (code, ite) => {
		selectedMap.value[code] = ite.classificationId;
		updateClassifyIdParam();
		params.value.page = 1;
		getCourseData();
	};

	// 点击“全部”
	const handleAllClick = (code) => {
		selectedMap.value[code] = 'all';
		updateClassifyIdParam();
		params.value.page = 1;
		getCourseData();
	};

	// 根据classifyId匹配分类并选中
	const matchClassifyById = () => {
		if (!classifyId.value || !classifyList.value.length) {
			return;
		}

		const targetId = classifyId.value.toString();

		let isMatched = false;
		classifyList.value.forEach((group) => {
			if (isMatched) return; // 已匹配则终止循环

			// 在当前分类组的子分类中查找目标ID
			const matchedChild = group.children?.find(
				(child) => child.classificationId.toString() === targetId
			);

			if (matchedChild) {
				// 匹配成功：更新选中状态
				selectedMap.value[group.code] = matchedChild.classificationId;
				isMatched = true;
			}
		});

		if (!isMatched) {
			// console.warn(`未找到ID为${targetId}的分类`);
		} else {
			// 匹配成功后更新参数并重新加载课程
			updateClassifyIdParam();
			params.value.page = 1;
			getCourseData();
		}
	};

	// 更新分类参数
	const updateClassifyIdParam = () => {
		const selectedIds = Object.values(selectedMap.value).filter(
			(value) => value !== 'all'
		);
		params.value.classifyId = selectedIds.join(',');
	};

	// 展开/收起分类
	const toggleGlobal = () => {
		isGlobalExpanded.value = !isGlobalExpanded.value;
	};

	// 控制显示的分类组
	const visibleGroups = computed(() => {
		return isGlobalExpanded.value 
			? classifyList.value 
			: classifyList.value.slice(0, 2);
	});

	// 跳转课程详情
	const getCourse = (item) => {
		const storedCode = localStorage.getItem('cartoonInviteCode') || '';
		router.push({
			name: 'home',
			query: {
				courseId: item.courseId,
				code: storedCode
			}
		});
	};

	// 返回上一页
	const handleBack = () => {
		router.back();
	};

	// 初始化
	onMounted(() => {
		// 1. 从路径参数获取分类ID（如/classify/123中的123）
		const pathId = route.params.id;
		if (pathId) {
			classifyId.value = pathId;
			params.value.classifyId = pathId;
		}

		// 2. 加载数据并匹配分类
		// 先加载分类数据，再加载课程，最后匹配选中状态
		getClassifyData().then(() => {
			// 分类数据加载后，执行匹配逻辑
			matchClassifyById();
		});
		getCourseData();

		// 3. 绑定滚动监听
		window.addEventListener('scroll', handleScroll, true);
	});

	// 卸载时清理
	onUnmounted(() => {
		window.removeEventListener('scroll', handleScroll, true);
	});
</script>

<style scoped lang="scss">
	/* 样式保持不变 */
	.classify-box {
		.classify-list {
			margin-left: 20px;
			margin-right: 20px;
			display: -webkit-box;
			align-items: flex-start;
			justify-content: flex-start;
			margin-bottom: 15px;
			width: calc(100% - 40px);

			span {
				padding: 4px 12px;
				border: 1px solid #fff;
				display: inline-block;
				border-radius: 20px;
				font-size: 14px;
			}

			.all {
				padding: 4px 20px !important;
				border: 1px solid #fff;
				display: inline-block;
				border-radius: 20px;
				font-size: 14px;
				font-weight: 540;
			}

			.active {
				color: #fcae06 !important;
				border-color: #fcae06 !important;
			}

			.classify {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				flex-wrap: wrap;
				width: calc(100% - 66px);
			}
		}
	}

	.global-toggle-btn {
		text-align: center;
		color: #409eff;
		cursor: pointer;
		font-size: 16px;
		padding-bottom: 10px;
		border-bottom: 1px dashed #e1e1e1;
	}

	.course-list {
		display: flex;
		flex-wrap: wrap;
		padding-top: 10px;
		margin-left: 10px;
		width: calc(100% - 10px);
		gap: 10px;
		.course {
			width: calc(33.3% - 30px);
			display: flex;
			flex-direction: column;
			text-align: center;
			margin-right: 10px;
			margin-bottom: 10px;
			.tu-box {
				position: relative;
				font-size: 14px;
				.status {
					position: absolute;
					top: 3px;
					right: 3px;
					color: #ff0000;
					font-weight: 500;
					text-shadow:
						0 0 2px #fff,
						/* 轻微模糊使边缘更平滑 */
						-1px -1px 0 #fff,
						-1px 0 0 #fff,
						-1px 1px 0 #fff,
						0 -1px 0 #fff,
						0 1px 0 #fff,
						1px -1px 0 #fff,
						1px 0 0 #fff,
						1px 1px 0 #fff;
				}
				.status1 {
					position: absolute;
					top: 3px;
					right: 3px;
					color: #409eff;
					font-weight: 500;
					text-shadow:
						0 0 2px #fff,
						/* 轻微模糊使边缘更平滑 */
						-1px -1px 0 #fff,
						-1px 0 0 #fff,
						-1px 1px 0 #fff,
						0 -1px 0 #fff,
						0 1px 0 #fff,
						1px -1px 0 #fff,
						1px 0 0 #fff,
						1px 1px 0 #fff;
				}
			}

			h4 {
				margin-top: 10px !important;
				font-size: 14px;
				font-weight: normal;
				margin-bottom: 5px !important;
				display: inline-block;
				color: #303133;
				text-overflow: ellipsis;
				width: 100%;
				overflow: hidden;
				white-space: nowrap;
			}

			p {
				font-size: 14px;
				color: #606166;
			}
		}
	}
	.load-status {
		padding: 20px 0;
		text-align: center;
		color: #666;
		font-size: 14px;
	}
	/* 骨架屏样式 */
	::v-deep .t-skeleton__row {
		margin-bottom: 20px;
		display: flex;
		gap: 10px;
	}
	
	::v-deep .t-skeleton__image {
		width: 100% !important;
		height: 160px !important;
		border-radius: 4px;
	}
</style>